package http

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"wechat-push/pkg/logger"
)

var (
	tr = &http.Transport{
		MaxIdleConns:       10,
		IdleConnTimeout:    300 * time.Second,
		DisableKeepAlives:  true,
		DisableCompression: false,
	}

	httpClient = &http.Client{Transport: tr, Timeout: 5 * time.Second}
)

func Get(url string, returnResponse interface{}) error {
	return request(url, http.MethodGet, "", returnResponse)
}

func Post(url string, data interface{}, returnResponse interface{}) error {
	return request(url, http.MethodPost, data, returnResponse)
}

func request(httpUrl, method string, data interface{}, returnResponse interface{}) error {
	return requestByHeader(httpClient, httpUrl, method, data, returnResponse)
}

func requestByHeader(httpClient *http.Client, httpUrl, method string, data interface{}, returnResponse interface{}) error {
	param, _ := json.Marshal(data)
	reqBody := string(param)
	req, err := http.NewRequest(method, httpUrl, strings.NewReader(reqBody))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	// 防止超时多试几次
	var res *http.Response
	res, err = httpClient.Do(req)
	for i := 0; err != nil; i++ {
		time.Sleep(2 * time.Second)
		// reset Request.Body
		req.Body = ioutil.NopCloser(strings.NewReader(reqBody))
		res, err = httpClient.Do(req)
		if err == nil {
			break
		}
		if i > 3 {
			logger.Log.Errorf("after %d tries httpClient.Do error  ", i)
			return err
		}
	}

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	if err = json.Unmarshal(body, returnResponse); err != nil {
		logger.Log.Error("json Unmarshal response error:", string(body), "\nerr:", err)
	}
	return err
}
